package com.seelyn.ddvideo.spider;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.seelyn.ddvideo.event.ParseErrorEvent;
import com.seelyn.ddvideo.event.SystemEventPublisher;
import com.seelyn.ddvideo.model.Video;
import com.seelyn.ddvideo.model.VideoPlayer;
import com.seelyn.ddvideo.service.VideoService;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor;

import java.util.Date;
import java.util.List;

/**
 * @author slacrey
 * @since 2017/6/16
 */
public class YoukuVideoPageProcessor implements PageProcessor {

    private VideoService videoService;
    private SystemEventPublisher eventPublisher;

    private Site site = Site.me().setDomain("vip.youku.com")
            .setCharset("UTF-8")
            .setSleepTime(500)
            .setUserAgent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_2) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.65 Safari/537.31");

    public YoukuVideoPageProcessor(SystemEventPublisher eventPublisher, VideoService videoService) {
        this.eventPublisher = eventPublisher;
        this.videoService = videoService;
    }

    @Override
    public void process(Page page) {

        JSONObject responseObject = page.getJson().toObject(JSONObject.class);
        String code = responseObject.getString("code");
        if ("20000".equals(code)) {
            JSONObject resultObject = responseObject.getJSONObject("result");
            if (resultObject == null) {
                eventPublisher.publishParseError(new ParseErrorEvent(null, FromSiteEnum.YOUKU, MovieTypeEnum.all, PageTypeEnum.LIST));
                return;
            }
            String type = resultObject.getString("tag");

            JSONArray resultArray = resultObject.getJSONArray("result");
            if (resultArray == null || resultArray.isEmpty()) {
                eventPublisher.publishParseError(new ParseErrorEvent(null, FromSiteEnum.YOUKU, MovieTypeEnum.all, PageTypeEnum.LIST));
                return;
            }
            JSONObject itemObj;
            Video video;
            int count = resultArray.size() - 1;
            for (int i = count; i >= 0; i--) {

                video = new Video();
                itemObj = resultArray.getJSONObject(i);
                String title = itemObj.getString("showname");
                String remarks = itemObj.getString("showsubtitle");
                String showlastupdateText = itemObj.getString("showlastupdate");

                Date online_time = itemObj.getDate("onlinetime");
                Float score = itemObj.getFloat("reputation");
                String picUrl = itemObj.getString("show_vthumburl");
                String vid = itemObj.getString("firstepisode_videoid");
                Date createTime = itemObj.getDate("showlastupdate");
                String playUrl = itemObj.getString("firstepisode_videourl");
                String updateText = itemObj.getString("display_status");

                video.setTitle(title);
                video.setRemarks(remarks);
                video.setVid(vid);
                video.setUpdateText(updateText);
                video.setScore(score);
                video.setOnlineTime(new Date().getTime());
                video.setCreateTime(createTime.getTime());
                video.setPicUrl(picUrl);
                video.setDelFlag(false);

                Video oldVideo = videoService.findVideoByTitle(title);
                if (oldVideo != null) {
                    video.setId(oldVideo.getId());
                    video.setVideoFroms(oldVideo.getVideoFroms());
                }

                if ("10005".equals(type)) {
                    //电影
                    video.setMovieType(MovieTypeEnum.movie.ordinal());

                    List<VideoPlayer> players = video.getPlayers(FromSiteEnum.YOUKU);

                    VideoPlayer videoPlayer = new VideoPlayer();
                    videoPlayer.setOrder(1);
                    videoPlayer.setUrl(playUrl);
                    videoPlayer.setName(title);

                    //清空以前存在的播放地址
                    players.clear();
                    players.add(videoPlayer);

                    videoService.saveVideo(video);

                } else if ("10006".equals(type)) {
                    // 电视剧
                    video.setMovieType(MovieTypeEnum.tv.ordinal());
                    Spider.create(new YoukuVideoInfoTVProcessor(eventPublisher, videoService, video))
                            .addUrl(playUrl)
                            .run();

                } else if ("10007".equals(type)) {
                    // 动漫
                    video.setMovieType(MovieTypeEnum.cartoon.ordinal());
                    Spider.create(new YoukuVideoInfoCartoonProcessor(eventPublisher, videoService, video))
                            .addUrl(playUrl)
                            .run();
                }

            }

        }
    }

    @Override
    public Site getSite() {
        return site;
    }
}
